# name: discourse-reply-required
# about: Required reply before sees the attachment
# version: 0.12
# authors: Erick Guan (fantasticfears@gmail.com)

register_asset "stylesheets/reply-required.css"

REPLY_REQUIRED_REGEXP = /\[details="回复本帖以查看隐藏内容"\]/i
REPLY_REQUIRED_TOPIC_CUSTOM_FIELD_NAME = 'reply-required'

def set_topic_custom_field_reply_required(topic_id, flag)
  tf = TopicCustomField.find_or_initialize_by(topic_id: topic_id, name: REPLY_REQUIRED_TOPIC_CUSTOM_FIELD_NAME)
  tf.value = flag
  tf.save!
end

  # serializer fields will be added inside after_initialize to ensure classes are loaded

after_initialize do
  # Use Discourse's add_to_serializer to expose flags safely on the TopicView
  add_to_serializer(:topic_view, :reply_required) do
    next false unless object && object.topic
    cf = TopicCustomField.find_by(topic_id: object.topic.id,
                                  name: REPLY_REQUIRED_TOPIC_CUSTOM_FIELD_NAME)
    cf && (cf.value == "t" || cf.value == "true")
  end

  add_to_serializer(:topic_view, :is_replied) do
    # scope may be a User, a Guardian, or another context object. Resolve to a User safely.
    user = nil
    if scope.respond_to?(:id) && scope.class.name == 'User'
      user = scope
    elsif scope.respond_to?(:current_user)
      user = scope.current_user
    elsif scope.respond_to?(:user)
      user = scope.user
    end

    next false unless user && object && object.topic
    Post.exists?(topic_id: object.topic.id, user_id: user.id)
  end
  # When create
  DiscourseEvent.on(:topic_created) do |topic, opts, user|
    # Existing block
    if REPLY_REQUIRED_REGEXP.match opts[:raw]
      set_topic_custom_field_reply_required(topic.id, true)
    else
      set_topic_custom_field_reply_required(topic.id, false)
    end
  end

  # When first post edits
  DiscourseEvent.on(:validate_post) do |post|
    # Existing block
    if post.is_first_post?
      if REPLY_REQUIRED_REGEXP.match(post.raw)
        set_topic_custom_field_reply_required(post.topic.id, true)
      else
        set_topic_custom_field_reply_required(post.topic.id, false)
      end
    end
  end

end
